#define _XOPEN_SOURCE 1

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

//#include "code_retour.h"
#include "config/config.h"
#include "get_index.h"
#include "cpp.h"
#include "authentification.h"
#include "real_path.h"
#include "cgi.h"
#include "content.h"

#include "serveur.h"

char *depart="depart";

int        sock_tab    [NCONNS] = { [ 0 ... NCONNS-1 ] = -1 };
pthread_t  pid_tab     [NCONNS] = { [ 0 ... NCONNS-1 ] = -1 };//moyen de pas use ce tableau
log_client log_clients [NCONNS];

int nsocks = 0;
pthread_mutex_t mutex;



void 
perror_and_exit_whenever(int assertion)
{
  if (assertion)
    {
      perror("Error ");
      exit(EXIT_FAILURE);
    }
}



void *
requete(void * fdc)
{
  int i = (int) fdc;

  
  char *requete = recupere_requete(sock_tab[i]);
  if (requete == NULL)
    {
      deconnecter_client_thread(i);
      return NULL;
    }
  

  requete_t req = traiter_requete(requete);
  free(requete);
  requete = NULL;
  char *mauvaise_requete = "bad request";

  
  if (req->User_Agent)
    {
      log_clients[i].user_agent = malloc(sizeof(char)*(strlen(req->User_Agent)+1));
      strcpy(log_clients[i].user_agent,req->User_Agent);
    }
 

  if (req->methode > -1)
    {
      
      char *meth;
      switch(req->methode)
	{
	case 0:
	  meth = "GET";
	  break;
	case 1:
	  meth = "HEAD";
	  break;
	default:
	  meth = "POST";
	  break;
	}

      log_clients[i].requete = malloc(sizeof(char)*(strlen(meth)+strlen(req->url_demande)+2));
      sprintf(log_clients[i].requete,"%s %s",meth,req->url_demande);

      get_page(sock_tab[i],req,&log_clients[i]);
    }
  else
    {
      log_clients[i].requete= malloc(sizeof(char)*(strlen(mauvaise_requete)+1));
      strcpy(log_clients[i].requete,mauvaise_requete);
      
      envoyer_code(sock_tab[i],requete_mauvaise,&log_clients[i],BAD_REQUEST);
      
      int fd = open(BAD_REQUEST, O_RDONLY);
      perror_and_exit_whenever(fd == -1);
      copier_fichier(sock_tab[i],fd);
      close(fd);
    }



  liberer_requete(req);
  deconnecter_client_thread(i);
  return NULL;
}

void
deconnecter_client_thread(int indice)
{
  pthread_mutex_lock(&mutex);
  rentrer_log(&log_clients[indice]);
  printf("%s deconnecte\n\n",log_clients[indice].nom);
  close(sock_tab[indice]);

  liberer_log(&log_clients[indice]);
  sock_tab[indice] = -1;
  nsocks--;
  //  pthread_kill(pid du main,usr1);
  pthread_mutex_unlock(&mutex);
}

void
liberer_log(log_client *log)
{
  if(log->ip)
    free(log->ip);

  if (log->nom)
    free(log->nom);
  if (log->date_connexion)
    free(log->date_connexion);
  if (log->requete)
    free(log->requete);

  if (log->code_retour)
    free(log->code_retour);
  
  if (log->user_agent)
    free(log->user_agent);
  
  memset(log,0,sizeof(struct log_client));
  
}

void
usage()
{
  fprintf(stderr,"Usage : ./serveur [fonctionnement]\nfonctionnement = thread ou select\n");
  exit(EXIT_FAILURE);
}

int
main(int argc, char *argv[])
{
  //TESTER ARGS POUR SAVOIR SI ON UTILISE SELECT OU THREAD §
  if (argc < 2 || (strcmp(argv[1],"thread") != 0 && strcmp (argv[1],"select")))
    usage();


  //open fichier log d'erreurs et rediriger la sortie derreur
  int fderr = open(LOG_ERROR,O_WRONLY | O_CREAT | O_APPEND, 0600);
  if (fderr == -1)
    {
      perror("error log\n");
      exit(1);
    }
  dup2(fderr,2);
  close(fderr);
  


  int sock = socket(AF_INET,SOCK_STREAM,0);
  pthread_mutex_init(&mutex,NULL);
  
  struct sockaddr_in addr;
  socklen_t socklen = sizeof addr;

  struct sockaddr_in sin;
  memset(&sin, 0, sizeof sin);


  
  sin.sin_family = AF_INET;
  sin.sin_port = htons(PORT);

  int b = 1;

  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,&b,sizeof(b));


  if (bind(sock, (struct sockaddr*)&sin,sizeof sin) == -1)
    {
      perror("bind problem");
      exit(1);
    }

  if (listen(sock, 1)== -1)
    {
      perror("listen problem");
      exit(1);
    }
  
  
  printf("connecte, bind et listen reussis\n");

  if (strcmp(argv[1],"thread")==0)
    {

      pthread_attr_t thread_attr;

      if (pthread_attr_init (&thread_attr) != 0) {
	fprintf (stderr, "pthread_attr_init error");
	exit (1);
      }

      if (pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED) != 0) {
	fprintf (stderr, "pthread_attr_setdetachstate error");
	exit (1);
      }

      while(1)//il faut faire une version avec select
	{      
	  for (int i = 0; i < NCONNS; i++) 
	    {
	      if (sock_tab[i] == -1){		
		
		sock_tab[i] = accept(sock,(struct sockaddr*)&addr,&socklen);
		nsocks++;
		
		printf("nouveau client\n");
			    
		init_log(&addr,&log_clients[i]);
	    
		pthread_create(&pid_tab[i],&thread_attr, requete, (void *)i);
		break;
	      }
	    }

	  //pause ici -> faire sigaction() pour debloquer //faire masque avant ?hmmm
	}
    }

  else //select
    {

    }

  close(sock);

  return EXIT_SUCCESS;
}


void
envoyer_chaine(int isock, char* chaine)
{
  int r = write(isock,chaine,sizeof(char)*strlen(chaine) );
  perror_and_exit_whenever(r <= 0);
   
}

void
envoyer_code(int isock, char* code_retour,log_client *logc,char *url)
{
  char *content_type = get_content_type(url);

  logc->code_retour = malloc(sizeof(char)*(strlen(code_retour)+1));
  strcpy(logc->code_retour,code_retour);
  
  envoyer_chaine(isock,code_retour);
  envoyer_chaine(isock,content);
  if (content_type)
    envoyer_chaine(isock,content_type);

}

void
get_page(int isock, requete_t req, log_client *logc)
{
  if (!req->url)
    {
      //fichier demande n'existe pas
      envoyer_code(isock, requete_not_found,logc,NOT_FOUND);
      
      if (req->methode == head)
	return;//on affiche que les entete

      int fd = open(NOT_FOUND,O_RDONLY);
      perror_and_exit_whenever(fd == -1);
      copier_fichier(isock,fd);
      close(fd);
      
      return ;
    }
  
  if (!strstr(req->url,ROOT) || strstr(req->url,PSWDFILE))
    {
      
      
      //forbidden
      envoyer_code(isock,requete_forbidden,logc,FORBIDDEN);
      if (req->methode == head)
	return;//on affiche que les entete

      int fd = open(FORBIDDEN,O_RDONLY);
      perror_and_exit_whenever(fd == -1);
      copier_fichier(isock,fd);
      close(fd);
      
      return;
    }
    

  
  if(strstr(req->url,"/auth/"))
    {
      if (!authorization(req->Authorization))
	{
	  logc->code_retour = malloc(sizeof(char)*(strlen(requete_unauthorized)+1));
	  strcpy(logc->code_retour,requete_unauthorized);
	  envoyer_chaine(isock,requete_unauthorized);
	  envoyer_chaine(isock,authenticate);
	  
	  return;
	}
    }



  
  if (strstr(req->url,"/cgi-bin/"))
    {
      logc->code_retour = malloc(sizeof(char)*(strlen(requete_ok)+1));
      strcpy(logc->code_retour,requete_ok);
      envoyer_chaine(isock,requete_ok);


      if (req->methode == head)
	{
	  envoyer_chaine(isock,content);
	  envoyer_chaine(isock,content_html);
	  return;
	}

      cgi(req->url,isock);
      return;
    }

  envoyer_code(isock,requete_ok,logc,req->url);
  if (req->methode == head)
	return;//on affiche que les entete
  
    
  if (est_dossier(req->url))
    {
      char *existe_index = index_existe(req->url);
	
      if (existe_index == NULL)
	{
	  char *path_cpy = strstr(req->url,ROOT);
	  char *index =generer_index(path_cpy+strlen(ROOT),"index");
	    
	  if (index != NULL)
	    {
	      int r = write(isock,index,sizeof(char)*(strlen(index)+1));
	      perror_and_exit_whenever(r <= 0);
	      envoyer_chaine(isock,"\n\n");
		
	      free(index);
	      index = NULL;
	    }
	    
	  else
	    perror_and_exit_whenever(1);
	    
	}
      else
	{
	  char *new_path = malloc(sizeof(char)*(strlen(req->url)+strlen(existe_index)+2));
	  //2 car on rajoute aussi '/'
	    
	  strcpy(new_path,req->url);
	  strcat(new_path,"/");
	  strcat(new_path,existe_index);
	    
	  free(existe_index);
	    
	  int fdindex = open(new_path,O_RDONLY);
	  perror_and_exit_whenever(fdindex == -1);
	  copier_fichier(isock,fdindex);
	  close(fdindex);
	    
	    
	  free(new_path);
	}
    }
  else //on reclame un fichier
    {
      if (strstr(req->url,"/cpp/")!= NULL)
	{
	  preprocesser_cpp(req->url/*/"www/cpp/test.html.cpp"*/,isock);
	}
      else
	{
	  int fd = open(req->url,O_RDONLY);
	  perror_and_exit_whenever(fd == -1);
	  copier_fichier(isock,fd);
	  close(fd);
	      
	}
    }
    
}
  



void 
init_log(struct sockaddr_in* addr,log_client* log)
{
  //initialise qu'une partie des logs, le reste est fait durant le traitement de la requete
  
  char serv[SERV_SIZE]; 
  char name[BUFFER_SIZE];
  

  int gn =  getnameinfo((struct sockaddr*)addr, sizeof *addr,
			name, BUFFER_SIZE,
			serv, SERV_SIZE,0);
		
  perror_and_exit_whenever(gn != 0);
  
  time_t t = time(NULL);
  char *date = asctime(localtime(&t));
  char *ip = inet_ntoa(addr->sin_addr);
  
  log->ip = malloc(sizeof(char)*(strlen(ip)+1));
  log->nom = malloc(sizeof(char)*(strlen(name)+1));
  log->date_connexion = malloc(sizeof(char)*(strlen(date)+1));

  strcpy(log->ip,ip);
  strcpy(log->nom,name);
  strcpy(log->date_connexion,date);

  /*log->user_agent = NULL;
  log->code_retour = NULL;
  log->requete     = NULL;
  */
    
}
  

void
rentrer_log(log_client *log)
{
  FILE* log_f = fopen(LOG_FILE,"a");
  perror_and_exit_whenever(!log_f);

 
  fprintf(log_f,"\n%s",log->date_connexion);
  fprintf(log_f,"%s\n",log->ip);
  fprintf(log_f,"%s\n",log->nom);
  fprintf(log_f,"%s\n",log->user_agent);
  fprintf(log_f,"%s\n",log->requete);
  fprintf(log_f,"%s\n",log->code_retour);
    
  fclose(log_f);
}


void
copier_fichier(int fd_dst,int fd_src)
{
  char buff_copier[BUFFER_SIZE];
  int r_copier;
  while ((r_copier = read(fd_src,buff_copier,BUFFER_SIZE)) > 0)
    if (write(fd_dst,buff_copier,r_copier) <= 0)
      perror_and_exit_whenever(1);
  

}


